#include <stdlib.h>
#include <stdio.h>
#include "script_memory.h"

#ifdef SCRIPT_MEMORY_DEBUG

struct script_memory_t{
	void	*p;
	int		size;
	char	desc[256];
	struct script_memory_t *next;
};

static struct script_memory_t *g_memory = NULL;

static void add_memory(struct script_memory_t *m)
{
	if(g_memory == NULL){
		g_memory = m;
		return;
	}

	struct script_memory_t *n = g_memory;
	while(n->next){
		n = n->next;
	}
	n->next = m;
}

static void del_memory(void *p)
{
	struct script_memory_t *m = g_memory;
	struct script_memory_t *prev = NULL;
	while(m){
		if(m->p == p){
			if(prev == NULL){
				g_memory = g_memory->next;
			}else{
				prev->next = m->next;
			}
			free(m);
			return;
		}
		prev = m;
		m = m->next;
	}
}

void show_script_memory(void)
{
	struct script_memory_t *m = g_memory;
	int total = 0;
	int index = 0;
	while(m){
		printf("%-3d. %p size:%d desc:%s\n",index++,m->p,m->size,m->desc);
		total += m->size;
		m = m->next;
	}

	printf("---------------------------------\n");
	printf("memory total: %d\n",total);
}

void *_script_calloc(int size, int num,char *file, int line)
{
	void *data = calloc(size,num);
	if(data){
		struct script_memory_t *m = calloc(1,sizeof(struct script_memory_t));
		m->p = data;
		m->size = size*num;
		sprintf(m->desc,"%s - %d",file,line);
		add_memory(m);
	}
	return data;
}

void _script_free(void *data)
{
	del_memory(data);
	free(data);
}

#endif
